<template>
    <div class="app-container">

        <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch">
            <el-form-item label="字段中文名" prop="fieldCaption">
                <el-input v-model="queryParams.fieldCaption" placeholder="请输入字段中文名" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="字段名称" prop="fieldName">
                <el-input v-model="queryParams.fieldName" placeholder="请输入字段名称" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="字段类型" prop="fieldType">
                <el-select v-model="queryParams.fieldType" placeholder="请选择" clearable style="width: 240px">
                    <el-option v-for="dict in dict.type.basic_data_fieldtype" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="是否公共字段" prop="isCommon">
                <el-select v-model="queryParams.isCommon" placeholder="请选择" clearable style="width: 240px">
                    <el-option v-for="dict in isCommonOption" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="状态" prop="state">
                <el-select v-model="queryParams.state" placeholder="请选择" clearable style="width: 240px">
                    <el-option v-for="dict in stateOption" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="创建日期" prop="dateRange">
                <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8" ref="refbut">
            <el-col :span="1.5">

                <el-select v-model="queryParams.type" style="width:140px"  @change="handleChange">

                    <el-option v-for="(dict, index) in fileorupTypeOption" :key="index" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd"
                    v-hasPermi="['tenantManage:templateManage:basicData:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit"  @click="handleUpdate" :disabled="single"
                    v-hasPermi="['tenantManage:templateManage:basicData:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete"  @click="handleDelete" :disabled="multiple"
                    v-hasPermi="['tenantManage:templateManage:basicData:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload2"  @click="handleImport"
                    v-hasPermi="['tenantManage:infoManage:import']">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download"  @click="handleExport"
                    v-hasPermi="['tenantManage:infoManage:export']">导出</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download"  @click="handleExportAll"
                         v-hasPermi="['tenantManage:infoManage:export']">导出全部</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="basicDataList" :height="tableHeight" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="id"/>
            <el-table-column label="字段中文名" prop="fieldCaption" align="center" />
            <el-table-column label="字段名称" prop="fieldName" align="center" />
            <el-table-column label="字段类型" prop="fieldType" align="center" />
            <el-table-column label="字段长度" prop="fieldLength" align="center" />
            <el-table-column label="是否公共字段" prop="isCommon" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.isCommon=='1' ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="state" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.state=='1' ? '启用' : '未启用' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否主键" prop="bepk" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.bepk=='1' ? '主键' : '非主键' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否允许为空" prop="nullable" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.nullable=='true' ? '是' : '否' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="是否展示" prop="showModel" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.showModel=='1' ? '是' : '否' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="字段展示类型">
              <template slot-scope="scope">
                <el-select v-model="scope.row.showType" style="width:90px"  @change="handleTypeChange(scope.row)">
                  <el-option v-for="dict in dict.type.basic_data_showtype" :key="dict.label" :label="dict.label"
                             :value="dict.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="列宽" prop="thWidth" align="center" />
            <el-table-column label="对齐方式" prop="thAlign"></el-table-column>
        </el-table>

        <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


      <!-- 添加或修改角色配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="45%" style="margin-top:8%" append-to-body>
        <el-form ref="fieldForm" :model="fieldForm" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="字段中文名" prop="fieldCaption">
                <el-input v-model="fieldForm.fieldCaption" placeholder="1-20位（汉字/字母/中文小括号）" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="12"> <el-form-item label="字段名称" prop="fieldName">
              <el-input v-model="fieldForm.fieldName" placeholder="1-20位（大写字母/下划线）下划线不可为首尾" clearable />
            </el-form-item></el-col>
          </el-row>
          <el-row>
            <el-col :span="12"> <el-form-item label="字段类型" prop="fieldType">
              <el-select v-model="fieldForm.fieldType" placeholder="请选择" style="width: 100%;">
                <el-option v-for="dict in dict.type.basic_data_fieldtype" :key="dict.value" :label="dict.label" :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item></el-col>
            <el-col :span="12"> <el-form-item label="字段长度" prop="fieldLength">
              <el-input-number v-model="fieldForm.fieldLength" controls-position="right" placeholder="请输入数字，1-20位" style="width: 100%;"></el-input-number>
            </el-form-item></el-col>
          </el-row>
          <el-row>
            <el-col :span="12"><el-form-item label="列宽" prop="thWidth">
              <el-input-number v-model="fieldForm.thWidth" controls-position="right" placeholder="请输入数字，1-4位" style="width: 100%;"></el-input-number>
            </el-form-item></el-col>
            <el-col :span="12"> <el-form-item label="对齐方式" prop="thAlign">
              <el-select v-model="fieldForm.thAlign" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in thAlignOption" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item></el-col>
          </el-row>
          <el-row>
            <el-col :span="12"><el-form-item label="是否公共字段" prop="isCommon">
              <el-select v-model="fieldForm.isCommon" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in isCommonOption" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item></el-col>
            <el-col :span="12"> <el-form-item label="状态" prop="state">
              <el-select v-model="fieldForm.state" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in stateOption" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item></el-col>
          </el-row>
          <el-row>
            <el-col :span="12"><el-form-item label="是否主键" prop="bepk">
              <el-select v-model="fieldForm.bepk" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in bepkOption" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item></el-col>
            <el-col :span="12"> <el-form-item label="是否允许为空" prop="nullable">
              <el-select v-model="fieldForm.nullable" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in nullAbleoption" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item></el-col>
          </el-row>
          <el-row>
            <el-col :span="12"><el-form-item label="是否展示" prop="showModel">
              <el-select v-model="fieldForm.showModel" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in showModelOption" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item></el-col>
            <el-col :span="12"> <el-form-item label="字段展示类型" prop="showType">
              <el-select v-model="fieldForm.showType" placeholder="请选择" style="width: 100%;">
                <el-option v-for="dict in dict.type.basic_data_showtype" :key="dict.value" :label="dict.label" :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item></el-col>
          </el-row>
<!--          <el-row>-->
<!--            <el-col :span="24">-->
<!--              <el-form-item label="状态">-->
<!--                <el-radio-group v-model="state">-->
<!--                  <el-radio :label="0">开启</el-radio>-->
<!--                  <el-radio :label="1">关闭</el-radio>-->
<!--                </el-radio-group>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </el-row>-->



        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button  @click="resetlogin">重 置</el-button>
        </div>
      </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                   :action="upload.url + '?updateSupport=' + upload.updateSupport + '&type=' + queryParams.type" :disabled="upload.isUploading"
                   :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
<!--            <div class="el-upload__tip" slot="tip">-->
<!--              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的基础数据-->
<!--            </div>-->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                     @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import {addBasicData, delBasicData, getBasicData, listBasicData, updateBasicData, updateShowType} from "@/api/manage/basicData"
import estimateTableHeight from '@/mixins/estimateTableHeight'
import {getToken} from "@/utils/auth";


//vue项目中element-tabel自动计算高度
export default {
    dicts: ['basic_data_fieldtype','basic_data_showtype'],
    mixins: [estimateTableHeight], // 混入方法
    data() {
        const checkFieldCaption = (rule, value, callback) => {
          if (value) {
            var reg = /^(?!）)(?!.*?（$)[A-Za-z\u4E00-\u9FA5（）]{1,20}$/
            if (reg.test(value) === false) {
              callback(new Error('请输入1-20位（汉字/字母/中文小括号），）不可为首，（不可为尾'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        const checkFieldName = (rule, value, callback) => {
          if (value) {
            var reg = /^(?!_)(?!.*?_$)[A-Z_]{1,20}$/
            if (reg.test(value) === false) {
              callback(new Error('请输入1-20位（大写字母/下划线），下划线不可为首尾'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        const checkFieldLength = (rule, value, callback) => {
          if (value) {
            var reg = /^(?!0)[0-9]{1,20}$/
            if (reg.test(value) === false) {
              callback(new Error('请输入数字，1-20位'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        const checkthWidth = (rule, value, callback) => {
          if (value) {
            var reg = /^(?!0)[0-9]{1,4}$/
            if (reg.test(value) === false) {
              callback(new Error('请输入数字，1-4位'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            label: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 基础数据表格数据
            basicDataList: [],
            // 用户导入参数
            upload: {
              // 是否显示弹出层（用户导入）
              open: false,
              // 弹出层标题（用户导入）
              title: "",
              // 是否禁用上传
              isUploading: false,
              // 是否更新已经存在的基础数据
              updateSupport: 0,
              // 设置上传的请求头部
              headers: { Authorization: "Bearer " + getToken() },
              // 上传的地址
              url: process.env.VUE_APP_BASE_API + "/manage/yqfields/importData"
            },
            // 查询参数
            queryParams: {
                pageNum:1,
                pageSize:10,
                fieldCaption: undefined,
                fieldName: undefined,
                fieldType: undefined,
                isCommon: undefined,
                state: undefined,
                type: 0,
                createTime: undefined,
                createTime2: undefined
            },
            // 表单参数
            fieldForm: {},
            // 日期范围
            dateRange: [],

            //选择案卷层和文件层
            type: "",
            fileorupTypeOption: [
              {value: '0',label: '组件'},
              {value: '1',label: '组卷'},
              {value: '2',label: '电子文件'},
              {value: '3',label: '项目'},
            ],
            //选择字段展示类型
            showType: "",
            // 选择对齐方式
            thAlignOption: [
              {value: 'left',label: '左对齐'},
              {value: 'center',label: '居中'},
              {value: 'right',label: '右对齐'}
            ],
            // 选择是否公共字段
            isCommonOption: [
              {value: '0',label: '否'},
              {value: '1',label: '是'}
            ],
            // 选择状态
            stateOption: [
              {value: '0',label: '未启用'},
              {value: '1',label: '启用'}
            ],
            // 选择是否主键
            bepkOption: [
              {value: '0',label: '非主键'},
              {value: '1',label: '主键'}
            ],
            // 选择是否允许为空
            nullAbleoption: [
              {value: 'false',label: '否'},
              {value: 'true',label: '是'}
            ],
            // 选择是否展示
            showModelOption: [
              {value: '0',label: '否'},
              {value: '1',label: '是'}
            ],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 表单校验
            rules: {
                fieldCaption: [
                  { required: true, message: "字段中文名不能为空", trigger: "blur" },
                  { required: true, trigger: 'blur', validator: checkFieldCaption }
                ],
                fieldName: [
                  { required: true, message: "字段名称不能为空", trigger: "blur" },
                  { required: true, trigger: 'blur', validator: checkFieldName }
                ],
                fieldType: [
                  { required: true, message: "字段类型不能为空", trigger: "blur" }
                ],
                fieldLength: [
                  { required: true, message: "字段长度不能为空", trigger: "blur" },
                  { required: true, trigger: 'blur', validator: checkFieldLength }
                ],
                thWidth: [
                    { trigger: 'blur', validator: checkthWidth }
                ],
                isCommon: [
                  { required: true, message: "是否公共字段不能为空", trigger: "blur" }
                ],
                state: [
                  { required: true, message: "状态不能为空", trigger: "blur" }
                ],
                bepk: [
                  { required: true, message: "是否主键不能为空", trigger: "blur" }
                ],
                nullable: [
                  { required: true, message: "是否允许为空不能为空", trigger: "blur" }
                ],
                showModel: [
                  { required: true, message: "是否展示不能为空", trigger: "blur" }
                ],
                showType: [
                  { required: true, message: "字段展示类型不能为空", trigger: "blur" }
                ]
            }
        }
    },
    mounted() {
      this.queryParams.type = this.fileorupTypeOption[0].value;
    },
  created() {
        this.queryParams.type = this.fileorupTypeOption[0].value;
        this.getList();
    },
    methods: {
      handleChange() {
        console.log(this.queryParams.type)
        this.getList()
      },
        table_index(index){
          return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
        },
        // 保存按钮
        submitForm: function () {
          this.$refs["fieldForm"].validate(valid => {
              if (valid) {
                if(this.fieldForm.id!=undefined){
                  updateBasicData(this.fieldForm).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  });
                }else{
                    addBasicData(this.fieldForm).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                    });
                }
              }
          })
        },
        // 重置按钮
        resetlogin() {
          this.reset();
          this.resetForm("fieldForm");
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          this.ids = selection.map(item => item.id)
          this.single = selection.length!==1
          this.multiple = !selection.length
          this.label = selection.map(item => item.fieldCaption)
        },
        /** 查询基础数据列表 */
        getList() {
            this.loading = true;
            listBasicData(this.queryParams).then(response => {
              this.basicDataList = response.rows;
              for (var i = 0; i < response.rows.length; i++) {
                // 渲染表格字段类型
                for (let j = 0; j < this.dict.type.basic_data_fieldtype.length; j++) {
                  if(response.rows[i].fieldType == this.dict.type.basic_data_fieldtype[j].value){
                    this.basicDataList[i].fieldType = this.dict.type.basic_data_fieldtype[j].label
                  }
                }
                // 渲染表格对齐方式
                for (let j = 0; j < this.thAlignOption.length; j++) {
                    if(response.rows[i].thAlign == this.thAlignOption[j].value){
                       this.basicDataList[i].thAlign = this.thAlignOption[j].label
                    }
                }
              }
              this.total = response.total;
              this.loading = false;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            if (this.dateRange.length != 0){
              this.queryParams.createTime = this.dateRange[0].toString()
              this.queryParams.createTime2 = this.dateRange[1].toString()
            }
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.queryParams.createTime = undefined;
            this.queryParams.createTime2 = undefined;
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 表单重置
        reset() {
            this.fieldForm = {
                id: undefined,
                fieldCaption: undefined,
                fieldName: undefined,
                fieldType: undefined,
                fieldLength: undefined,
                thWidth: undefined,
                thAlign: undefined,
                isCommon: undefined,
                state: undefined,
                bepk: undefined,
                nullable: undefined,
                showModel: undefined,
                showType: undefined,
                type: undefined
            };
            this.resetForm("fieldForm");
        },
        /** 新增按钮操作 */
        handleAdd() {
          this.reset();
          this.open = true;
          this.title = "添加基础字段";
          this.fieldForm.type = this.queryParams.type
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
          this.reset();
          const id = row.id || this.ids
          getBasicData(id).then(response => {
            this.fieldForm = response.data;
            this.open = true;
            this.title = "修改基础字段";
          });
        },
        /** 修改字段展示类型 */
        handleTypeChange(row) {
          this.form = {
            showType: row.showType,
            id: row.id
          }
          this.$modal.confirm('是否确认修改基础数据字段中文名为"' + row.fieldCaption + '"的字段展示类型？').then(function() {

          }).then(()=>{
            updateShowType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            });
          }).catch(() => {
            this.getList();
          });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
          const ids = row.id || this.ids;
          const label = row.fieldCaption || this.label
          this.$modal.confirm('是否确认删除基础数据字段中文名为"' + label + '"的数据项？').then(function () {
            return delBasicData(ids);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport(row) {
          const ids = row.id || this.ids;
          if (ids.length == 0) {
            this.$message({
              showClose: true,
              message: '请选择要导出的数据'
            });
          } else {
            this.queryParams.ids=ids.toString();
            this.download('/manage/yqfields/export', {
              ...this.queryParams
            }, `basicdata_${new Date().getTime()}.xlsx`)
          }
        },
        /** 导出全部按钮操作 */
        handleExportAll() {
          this.download('/manage/yqfields/export', {
            ...this.queryParams
          }, `basicdata_${new Date().getTime()}.xlsx`)
        },
        /**导入按钮操作 */
        handleImport() {
          this.upload.title = "基础数据导入";
          this.upload.open = true;
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
        },
        /** 下载模板操作 */
        importTemplate() {
          this.download('/manage/yqfields/importTemplate', {
          }, `basicdata_template_${new Date().getTime()}.xlsx`)
        },
        // 提交上传文件
        submitFileForm() {
          this.$refs.upload.submit();
        }
    }
}
</script>
